/*
 * (C) 2012	Sheng Yi
 * Implemention of getpwuid and getpwnam by using getpwent
 */
#include "apue.h"
#include <pwd.h>
#include <stddef.h>

struct passwd* getpwuid_u(uid_t uid);
struct passwd* getpwnam_u(const char* name);

int main()
{
	struct passwd* ptr;
	ptr = getpwnam_u("root");
	printf("root ID is %d\n", ptr->pw_uid);
	ptr = getpwnam_u("sheng");
	printf("sheng ID is %d\n", ptr->pw_uid);

	ptr = getpwent();
	if (ptr == NULL)
		printf("setpwent will call getpwent inside, and getpwent returns null when firstly called.\n");
	else
	{
		printf("getpwent returns first entry when is called firstly.\n");
		printf("user ID: %d, user name: %s\n", ptr->pw_uid, ptr->pw_name);
	}
	return 0;
}

struct passwd* getpwuid_u(uid_t uid)
{
	struct passwd* ptr;
	setpwent();
	while ((ptr = getpwent()) != NULL)
	{
		if (ptr->pw_uid == uid)
			break;
	}
	endpwent();
	return ptr;
}

struct passwd* getpwnam_u(const char* name)
{
	struct passwd* ptr;
	setpwent();
	while ((ptr = getpwent()) != NULL)
		if (strcmp(ptr->pw_name, name) == 0)
			break;
	endpwent();
	return ptr;
}
